package com.thrd.basicframework.utils;

import com.alibaba.android.arouter.utils.TextUtils;
import com.thrd.basicframework.LrcMusic;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: ${唐杰}
 * @date: 2021/4/9
 */
public class LrcUtils {
    public static ArrayList<LrcMusic> redLrc(InputStream in) {
        ArrayList<LrcMusic> alist = new ArrayList<LrcMusic>();
        //File f = new File(path.replace(".mp3", ".lrc"));
        try {
            //FileInputStream fs = new FileInputStream(f);
            InputStreamReader input = new InputStreamReader(in, "utf-8");
            BufferedReader br = new BufferedReader(input);
            String s = "";

            while ((s = br.readLine()) != null) {
                if (!TextUtils.isEmpty(s)) {
                    String lyLrc = s.replace("[", "");
                    String[] data_ly = lyLrc.split("]");
                    if (data_ly.length > 1) {
                        String time = data_ly[0];
                        String lrc = data_ly[1];
                        LrcMusic lrcMusic = new LrcMusic(lrcData(time), lrc);
                        alist.add(lrcMusic);
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return alist;
    }
    public static int lrcData(String time) {
        time = time.replace(":", "#");
        time = time.replace(".", "#");

        String[] mTime = time.split("#");

        //[03:31.42]
        int mtime = Integer.parseInt(mTime[0]);
        int stime = Integer.parseInt(mTime[1]);
        int mitime = Integer.parseInt(mTime[2]);

        int ctime = (mtime*60+stime)*1000+mitime*10;

        return ctime;
    }


    //二分查询
    public static  int binarysearch(List<LrcMusic> a, int value) {
        //   LogUtil.e(TAG,"开始二分查找");
        int low = 0;
        int high = a.size() - 1;
        int mid;
        while (low < high) {
            mid = (low + high) / 2;

            if ((mid + 1) >= a.size() || value >= a.get(mid).getTime() && value < a.get(mid + 1).getTime())
                return mid;
            if (value < a.get(mid).getTime())
                high = mid - 1;
            if (value > a.get(mid).getTime())
                low = mid + 1;

        }

        if(low ==high){
            return low;
        }
        return -1;
    }
}
